<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="30%"
    :before-close="handleClose"
  >
    <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="90px">
      <el-form-item label="公众号" prop="name">
        <el-input v-model="formData.name" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="次数" prop="number">
        <el-input v-model="formData.number" placeholder="阅读次数" clearable @change="isNumber" />
      </el-form-item>
      <el-form-item v-if="formData.number > 5" label="阅读类型" prop="is_fast">
        <el-radio-group v-model="formData.is_fast">
          <el-radio :label="true">快速</el-radio>
          <el-radio :label="false">按分钟</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.is_fast === false" label="间隔(分钟)" prop="minutes">
        <el-input v-model="formData.minutes" placeholder="每间隔多少分钟平均阅读多少次" clearable @change="isMinutes" />
      </el-form-item>
      <el-form-item label="是否定时" prop="is_timing">
        <el-radio-group v-model="formData.is_timing">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.is_timing" label="开始时间" prop="time" required>
        <el-date-picker
          v-model="formData.time"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
        />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" v-text="isBtnCloseTitle" />
      <el-button v-show="isEdit !== 'view'" type="primary" @click="SubmitForm" v-text="isBtnConfTitle" />
    </span>
  </el-dialog>
</template>

<script>
import { addArticleReading, editArticleReading, viewArticleReading, checkNumber } from '@/api/wechat_article_reading'

export default {
  // 接收父组件传递过来的值
  props: {
    vdialog: {
      type: Boolean,
      default: false
    },
    vtitle: {
      type: String,
      default: ''
    },
    visedit: {
      type: String,
      default: ''
    },
    vformid: {
      // 接收父组件传过来的ID
      type: Number,
      default: 0
    }
  },
  data() {
    const rulesCheckNumber = (rule, value, callback) => {
      checkNumber({ number: this.formData.number }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
          return
        } else {
          callback()
        }
      })
    }
    return {
      // 控制弹出框的显示与隐藏
      dialogVisible: false,
      title: '',
      isBtnCloseTitle: '',
      isBtnConfTitle: '',
      formData: {
        name: '',
        title: '',
        number: 1,
        is_fast: true,
        is_timing: false,
        minutes: 1,
        time: null
      },
      isEdit: '',
      formId: '',
      // rules 表单前验证
      rules: {
        name: [
          { required: true, message: '公众号名称必填', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '文章标题必填', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '阅读次数必填', trigger: 'blur' },
          { validator: rulesCheckNumber, trigger: 'blur' }
        ],
        is_fast: [
          { required: true, message: '阅读类型必选', trigger: 'change' }
        ],
        is_timing: [
          { required: true, message: '是否定时必选', trigger: 'change' }
        ],
        minutes: [
          { required: true, message: '分钟数必填', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    // 监听 父组件传递过来的props内的值并改变/赋值
    vdialog() {
      // dialogVisible 弹框的显示与隐藏
      this.dialogVisible = this.vdialog
      if (this.dialogVisible) {
        // formid 数据ID
        this.formid = this.vformid
        // isEdit 表单状态
        this.isEdit = this.visedit
        // title 弹框的标题
        this.title = this.vtitle
        // 状态判断
        if (this.isEdit === 'add') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '新增'
        } else if (this.isEdit === 'edit') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '编辑'
          this.viewForm()
        }
      }
    }
  },
  methods: {
    viewForm() {
      viewArticleReading(this.formid).then(res => {
        this.formData.name = res.data.name
        this.formData.title = res.data.title
        this.formData.number = res.data.number
        this.formData.is_fast = res.data.is_fast
        this.formData.is_timing = res.data.is_timing
        this.formData.minutes = res.data.minutes
        this.formData.is_job_id = res.data.is_job_id
        this.formData.time = res.data.time
      })
    },
    SubmitForm() {
      // 表单验证并新增/编辑
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.isEdit === 'add') {
            this.addForm()
          } else if (this.isEdit === 'edit') {
            this.editForm()
          } else {
            this.$notify.warning({
              type: 'warning',
              title: '警告',
              message: '表单非法操作',
              showClose: true,
              duration: 0
            })
          }
        }
      })
    },
    addForm() {
      addArticleReading(this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.message,
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    editForm() {
      editArticleReading(this.formid, this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: '编辑成功',
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    // 弹出框关闭后的函数
    handleClose(done) {
      // 子组件调用父组件方法，并传递参数 this.$emit('父组件的方法', '传递的参数')
      if (this.isEdit === 'view') {
        this.isEditStatus()
      } else {
        if (this.formData.username) {
          this.$confirm('确认取消/关闭？')
            .then(_ => {
              this.isEditStatus()
              done()
            })
            .catch(_ => {})
        } else {
          this.isEditStatus()
        }
      }
    },
    isEditStatus() {
      // this.$refs['form表单里面的ref值'].resetFields()
      this.$refs['ruleForm'].resetFields()
      this.formData = { name: '', title: '', number: 1, is_fast: true, minutes: 1, is_timing: false, time: null }
      this.$emit('changeShow', 'false', 0)
    },
    // 对 number 进行校验
    isNumber(event) {
      // eslint-disable-next-line no-unused-vars
      let fix
      if (typeof this.formData.number === 'string') {
        fix = Number(this.formData.number.replace(/\D/g, ''))
      }
      if (this.formData.number < 1) {
        fix = 1
      }
      this.formData.number = fix
    },
    isMinutes(event) {
      // eslint-disable-next-line no-unused-vars
      let fix
      if (typeof this.formData.minutes === 'string') {
        fix = Number(this.formData.minutes.replace(/\D/g, ''))
      }
      if (this.formData.minutes < 1) {
        fix = 1
      }
      this.formData.minutes = fix
    }
  }
}
</script>
